<template>
  <div class="node_setting">
    <div class="setting_title">指标输出</div>
    <div class="setting_item">
      <div
        ref="tableContainerRef"
        class="table_infinite_list"
        style="max-height: 600px; overflow: auto"
      >
        <el-table
          class="table_infinite_list_item"
          :data="form.indicatorOutputData"
          height="500"
          border
          style="width: 100%"
        >
          <el-table-column fixed type="index" label="序号" width="70" />
          <el-table-column prop="tableName" label="表名" width="70" />
          <el-table-column prop="name" label="字段名" width="70" />
          <el-table-column prop="type" label="type" width="70" />
          <el-table-column prop="typeName" label="数据类型" width="70" />
          <el-table-column prop="size" label="长度" width="70" />
          <el-table-column prop="digit" label="小数点" width="70" />
          <el-table-column prop="comment" label="备注" width="70" />
          <el-table-column prop="autoIncrement" label="自增" width="70" />
          <el-table-column prop="columnDef" label="默认值" width="70" />
          <el-table-column prop="nullable" label="是否为空" width="70" />
          <el-table-column prop="typeEnum" label="类型枚举" width="70" />
          <el-table-column prop="pk" label="是否为主键" width="70" />
        </el-table>
      </div>
      <el-button class="mt-4" type="primary" @click="showSql">查看sql</el-button>
      <div v-if="showSqlText" class="mt-4 sql-container">
        <el-input
          v-model="exmaineSqlResponse.sql"
          type="textarea"
          placeholder="SQL语句"
          :rows="6"
          readonly
        />
      </div>
    </div>
  </div>
</template>
<script lang="ts">
export default { name: "IndicatorOutputSetting" };
</script>
<script setup lang="ts">
import LogicFlow from "@logicflow/core";
import { MyLogicFlowPropertiesType } from "@/types/logic-flow";
import strategyManageAPI, {
  FieldColumnsConfig,
  IgIndicatorJoinParameter,
  JoinColumnsConfig,
  TableInfoConfig,
  ExmaineSqlResponse,
} from "@/api/strategy/strategyManage";
import { TableListParameter } from "@/api/strategy/strategy-index-database";
const props = defineProps<{
  lf?: LogicFlow;
  data: LogicFlow.NodeData | LogicFlow.EdgeData;
  parameter: TableListParameter;
}>();
const joinConnectedData = ref<any[]>([]);
const igIndicatorJoinParameter = reactive<IgIndicatorJoinParameter>({});
const joinType = ref<string[]>();
const tables = ref<string[]>();
const joinColumns = ref<JoinColumnsConfig[]>();
const columns = ref<TableInfoConfig[]>();
const form = ref({
  indicatorOutputData: [] as FieldColumnsConfig[],
  newTableName: "", // 新指标表名称;
});
const tableContainerRef = ref<HTMLElement | null>(null);
const isLoading = ref(false); // 加载状态
const exmaineSqlResponse = ref<ExmaineSqlResponse>({});
const showSqlText = ref(false); // 控制SQL文本框显示

// 提取数据结构
const extractedData = computed(() => {
  return joinConnectedData.value.map((item) => {
    return {
      joinType: item.joinType,
      joinColumns: item.relationData,
      tables: item.tables,
      columns: item.columns,
    };
  });
});

// 存储上一次的数据状态
const previousExtractedData = ref<any[]>([]);

function mergeObjectArrays(arr1: TableInfoConfig[], arr2: TableInfoConfig[]) {
  const merged = [...arr1, ...arr2];
  const unique: TableInfoConfig[] = [];

  for (const item of merged) {
    let isDuplicate = false;
    for (const existingItem of unique) {
      if (
        existingItem.tableName === item.tableName &&
        existingItem.columnName === item.columnName
      ) {
        isDuplicate = true;
        break;
      }
    }
    if (!isDuplicate) {
      unique.push(item);
    }
  }
  return unique;
}

async function handleQuery() {
  isLoading.value = true;
  try {
    igIndicatorJoinParameter.dataSourceId = props.parameter.id;
    igIndicatorJoinParameter.columns = columns.value;
    igIndicatorJoinParameter.joinColumns = joinColumns.value;
    igIndicatorJoinParameter.joinType = joinType.value;
    igIndicatorJoinParameter.tables = tables.value;
    // const response =
    await strategyManageAPI.Join(igIndicatorJoinParameter).then((data) => {
      form.value.newTableName = data.tableName!;
      form.value.indicatorOutputData = data.columns!.map((item) => ({
        ...item,
      }));
    });
    // 更新节点属性
    if (props.lf && props.data.id) {
      props.lf.setProperties(props.data.id, {
        ...props.data.properties,
        indicatorOutputData: form.value.indicatorOutputData,
        newTableName: form.value.newTableName,
      });
    }
  } catch (error) {
    console.error("数据加载出错:", error);
  } finally {
    isLoading.value = false;
  }
}

const showSql = async () => {
  showSqlText.value = true;
  // 检查对象是否为空或必要属性是否缺失
  if (
    Object.keys(igIndicatorJoinParameter).length === 0 ||
    !igIndicatorJoinParameter.dataSourceId
  ) {
    const prevDataStr = localStorage.getItem("previousExtractedData") || "";
    const prevData = JSON.parse(prevDataStr);
    if (prevData) {
      igIndicatorJoinParameter.dataSourceId = props.parameter.id;
      igIndicatorJoinParameter.joinType =
        prevData.length > 1
          ? prevData[0].joinType.concat(prevData[1].joinType)
          : prevData[0].joinType;
      igIndicatorJoinParameter.tables =
        prevData.length > 1
          ? ([...new Set([...prevData[0].tables, ...prevData[1].tables])] as string[])
          : prevData[0].tables;
      igIndicatorJoinParameter.joinColumns =
        prevData.length > 1
          ? [prevData[0].joinColumns, prevData[1].joinColumns]
          : [prevData[0].joinColumns];
      igIndicatorJoinParameter.columns =
        prevData.length > 1
          ? mergeObjectArrays(prevData[0].columns, prevData[1].columns)
          : prevData[0].columns;
    }
  }
  await strategyManageAPI.exmaineSql(igIndicatorJoinParameter).then((data) => {
    exmaineSqlResponse.value.sql = data.sql;
  });
};

watch(extractedData, (newData) => {
  // 比较数据是否发生变化
  const newDataStr = JSON.stringify(newData);
  const prevDataStr = localStorage.getItem("previousExtractedData") || "";
  const isDataChanged = newDataStr !== prevDataStr;

  if (isDataChanged) {
    joinType.value =
      newData.length > 1 ? newData[0].joinType.concat(newData[1].joinType) : newData[0].joinType;
    tables.value =
      newData.length > 1
        ? ([...new Set([...newData[0].tables, ...newData[1].tables])] as string[])
        : newData[0].tables;
    joinColumns.value =
      newData.length > 1
        ? [newData[0].joinColumns, newData[1].joinColumns]
        : [newData[0].joinColumns];
    columns.value =
      newData.length > 1
        ? mergeObjectArrays(newData[0].columns, newData[1].columns)
        : newData[0].columns;
    if (newData.length > 0 && !isLoading.value) {
      handleQuery();
    }
    // 更新上一次的数据状态
    localStorage.setItem("previousExtractedData", newDataStr);
    previousExtractedData.value = JSON.parse(newDataStr);
  }
});

watch(
  () => props.data,
  (newVal) => {
    const validTargetTypes = ["left_join", "right_join", "inner_join", "full_join"];
    const validTargetTypes2 = ["table_input"];
    const incomingEdges = props.lf?.getNodeIncomingEdge(props.data.id);
    const sourceNodes = incomingEdges?.map((edge) => {
      return props.lf?.getNodeModelById(edge.sourceNodeId);
    });
    const dataForm = sourceNodes?.map((sourceNode) => {
      const sourceProperties = sourceNode?.getProperties();
      console.log(sourceNode?.type!);
      if (validTargetTypes.includes(sourceNode?.type!)) {
        sourceProperties!.joinConnectedData = sourceProperties?.joinConnectedData;
      } else if (validTargetTypes2.includes(sourceNode?.type!)) {
        sourceProperties!.connectedData = sourceProperties?.connectedData;
      }
      return sourceProperties?.joinConnectedData;
    }) as any[];
    const {
      indicatorOutputData,
      newTableName,
      joinConnectedData: dataFromProps,
    } = newVal.properties as MyLogicFlowPropertiesType;
    form.value = {
      indicatorOutputData: indicatorOutputData || [],
      newTableName: newTableName || "",
    };
    joinConnectedData.value = dataForm || [];
    props.lf?.setProperties(newVal.id, {
      ...form.value,
    });
  },
  {
    immediate: true,
  }
);
</script>
<style lang="scss" scoped>
.setting-title {
  padding: 10px 0;
  margin-bottom: 10px;
  font-size: 16px;
  font-weight: bold;
  text-align: center;
  border-bottom: 1px solid #e9e9e9;
}

.setting-item {
  .setting-item-title {
    padding: 10px 0;
    margin-bottom: 10px;
    font-size: 14px;
    font-weight: bold;
    border-bottom: 1px solid #e9e9e9;
  }

  /* 设置表格的滚动条样式 */
  .el-table__body-wrapper {
    overflow-y: auto;
  }

  .table_infinite_list {
    height: calc(100% - 20px);
    padding: 0;
    margin: 0;
    list-style: none;
  }

  .table_infinite_list .table_infinite_list_item {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 20px;
    margin: 10px;
  }

  .table_infinite_list .table_infinite_list_item + .list-item {
    margin-top: 10px;
  }
}
</style>
